%==========================================================================
%=  This file is part of the Sound Restoration Project
%=  (c) Copyright Industrial Mathematics Institute
%=                University of South Carolina, Department of Mathematics
%=  ALL RIGHTS RESERVED
%=
%=  Author: Borislav Karaivanov
%==========================================================================

%==========================================================================
% List of the files on which this procedure depends:
%
% getBitDepthFromVideoObject.m
% Image processing toolbox
%
%==========================================================================

%==========================================================================
% The function "readVideoFrames" reads a specified range of frames from a
% given Matlab-generated video object with the option to convert them to
% grayscale if requested.
% INPUT: "videoObj" is a Matlab-generated video object.
% "frameRange" is a single integer or a row vector of two integers
% specifying the index of a single frame or a range of frames to be read
% from the given video object.
% "doConvertToGray" is an optional boolean specifying whether the read
% frames are to be converted to grayscale before returned.
% OUTPUT: "frameArr" returns an image array holding the pixel values read
% from the given video object.
% "bitDepth" returns the number of bits used to encode each pixel value in
% any single color channel.
%==========================================================================
function [frameArr, bitDepth] = readVideoFrames(videoObj, frameRange, doConvertToGray)

% Read in the specified frames.
frameArr = read(videoObj, [frameRange(1), frameRange(end)]);

% Get the bit depth per pixel per color channel.
bitDepth = getBitDepthFromVideoObject(videoObj);

% Convert to grayscale images, if requested, and provided the read pixels
% have three or more components (like RGB).
isMoreThanOneFrameRead = (frameRange(end) > frameRange(1));
if ( (nargin == 3)&&(doConvertToGray == true)&&(ndims(frameArr) == (3 + isMoreThanOneFrameRead)) )
    if (isMoreThanOneFrameRead == true)
        frameArr = rgb2gray(frameArr(:, :, 1:3, :));
    else
        frameArr = rgb2gray(frameArr(:, :, 1:3));
    end
end

return;
% end of the function "readVideoFrames"
